from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.database import get_db
from app.api.auth import get_current_user
from app.schemas.user import UserInDB

router = APIRouter()

# 创建案例
@router.post("/", response_model=schemas.CaseResponse, status_code=status.HTTP_201_CREATED)
def create_case(
    case: schemas.CaseCreate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    created_case = crud.case.create_case(db=db, case=case, created_by=current_user.id)
    return created_case

# 获取案例列表
@router.get("/", response_model=list[schemas.CaseResponse])
def read_cases(
    skip: int = 0,
    limit: int = 100,
    category: str = None,
    approved: str = None,
    search: str = None,
    db: Session = Depends(get_db)
):
    # 处理approved参数
    approved_bool = None
    if approved is not None:
        approved_bool = approved.lower() == 'true'
    
    cases = crud.case.get_cases(
        db, 
        skip=skip, 
        limit=limit, 
        category=category,
        approved=approved_bool,
        search=search
    )
    return cases

# 获取案例详情
@router.get("/{case_id}", response_model=schemas.CaseResponse)
def read_case(case_id: int, db: Session = Depends(get_db)):
    db_case = crud.case.get_case(db, case_id=case_id)
    if db_case is None:
        raise HTTPException(status_code=404, detail="Case not found")
    return db_case

# 更新案例
@router.put("/{case_id}", response_model=schemas.CaseResponse)
def update_case(
    case_id: int,
    case: schemas.CaseUpdate,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    db_case = crud.case.update_case(db, case_id=case_id, case=case)
    if db_case is None:
        raise HTTPException(status_code=404, detail="Case not found")
    return db_case

# 删除案例
@router.delete("/{case_id}", response_model=schemas.CaseResponse)
def delete_case(
    case_id: int,
    db: Session = Depends(get_db),
    current_user: UserInDB = Depends(get_current_user)
):
    db_case = crud.case.delete_case(db, case_id=case_id)
    if db_case is None:
        raise HTTPException(status_code=404, detail="Case not found")
    return db_case

# 搜索相似案例
@router.post("/search", response_model=list)
def search_cases(
    search_request: schemas.CaseSearch,
    db: Session = Depends(get_db)
):
    matches = crud.case.search_similar_cases(
        db, 
        query=search_request.query, 
        category=search_request.category
    )
    return [
        {
            "case_id": case.id,
            "title": case.title,
            "similarity_score": score
        }
        for case, score in matches
    ]